const Vue = require("vue")
const express = require("express")
const fs = require("fs")
const { createBundleRenderer } = require("vue-server-renderer")
const setupDevServer = require("./build/setup-dev-server")

const server = express()

// 是否是开发模式（NODE_ENV变量的值）
const isProd = process.env.NODE_ENV === "production"

let renderer, onReady
if (isProd) {
    const serverBundle = require("./dist/vue-ssr-server-bundle.json")
    const clientManifest = require("./dist/vue-ssr-client-manifest.json")
    const template = fs.readFileSync("./index.template.html", "utf-8")
    renderer = createBundleRenderer(serverBundle, {
        template,
        clientManifest
    })
} else {
    // 开发模式 -> 监视打包构建 -> 从新生成 renderer 渲染器
    onReady = setupDevServer(server, (serverBundle, clientManifest, template) => {
        renderer = createBundleRenderer(serverBundle, {
            template,
            clientManifest
        })
    })
}

// express.static 处理的是物理磁盘中的资源文件
server.use("/dist", express.static("./dist"))

const render = (req, res) => {
    renderer.renderToString({
        title: "拉钩教育",
        meta: `<meta name="description" content="拉钩教育">`
    }, (err, html) => {
        if (err) {
            return res.status(500).end("Internal Server Error")
        }

        res.setHeader("Content-Type", "text/html; charset=utf8")
        res.end(html)
    })
}

// 判断是开发环境还是生产环境
server.get("/", isProd ? render : async (req, res) => {
    //todo 等待有了 renderer 渲染器以后，调用 render 进行渲染（需要先等待打包构建）
    await onReady
    render(req, res)
})

server.listen(3000, () => {
    console.log("server running at port 3000")
})
